package services

import (
	"errors"

	"gitee.com/sweetsunnyflower/carpooling-server-go/pkg/config"
	"gitee.com/sweetsunnyflower/carpooling-server-go/pkg/logger"
	"github.com/ArtisanCloud/PowerWeChat/src/kernel"
	"github.com/ArtisanCloud/PowerWeChat/src/kernel/power"
	"github.com/ArtisanCloud/PowerWeChat/src/miniProgram"
	"github.com/ArtisanCloud/PowerWeChat/src/miniProgram/subscribeMessage/request"
	"github.com/spf13/cast"
)

type MiniProgramService struct {
	MiniProgramApp *miniProgram.MiniProgram
}

func NewMiniProgram() *MiniProgramService {
	// 置换openid
	MiniProgramApp, err := miniProgram.NewMiniProgram(&miniProgram.UserConfig{
		AppID:     config.GetString("wechat.miniprogram.appid"),  // 小程序appid
		Secret:    config.GetString("wechat.miniprogram.secret"), // 小程序app secret
		HttpDebug: true,
		Log: miniProgram.Log{
			Level: "debug",
			File:  config.GetString("wechat.log"),
		},
		// 可选，不传默认走程序内存
		Cache: kernel.NewRedisClient(&kernel.RedisOptions{
			Addr:     config.GetString("redis.host") + ":" + config.GetString("redis.port"),
			Password: config.GetString("redis.password"),
			DB:       config.GetInt("redis.database"),
		}),
	})

	logger.LogIf(err)

	return &MiniProgramService{
		MiniProgramApp,
	}
}

func (miniProgram *MiniProgramService) Login(code string) (string, error) {
	res, err := miniProgram.MiniProgramApp.Auth.Session(code)
	logger.LogIf(err)

	if err != nil {
		return "", err
	}

	logger.InfoJSON("Get openid", "Session Response", res)

	if res.OpenID == "" {
		return "", errors.New(res.ErrMSG)
	}

	return res.OpenID, nil
}

// 取消通知
func (miniProgram *MiniProgramService) SubscribeMessage(tripRiderId uint64, openId string) (bool, error) {

	data := &power.HashMap{
		"phrase1": power.StringMap{
			"value": "已预约",
		},
		"thing2": power.StringMap{
			"value": "Cycle",
		},
		"time3": power.StringMap{
			"value": "15:30",
		},
		"thing4": power.StringMap{
			"value": "兴业太古汇",
		},
		"thing5": power.StringMap{
			"value": "开课3小时前",
		},
	}
	res, err := miniProgram.MiniProgramApp.SubscribeMessage.Send(&request.RequestSubscribeMessageSend{
		ToUser:           openId,
		TemplateID:       config.Get("wechat.templatesid.cancel_trip_id"),
		Page:             "/pages/passenger/trips?id=" + cast.ToString(tripRiderId), // 行程详情页
		MiniProgramState: "developer",
		Lang:             "zh_CN",
		Data:             data,
	})
	if err != nil {
		return false, err
	}

	if res.ErrCode != 0 {
		return false, errors.New(res.ErrMSG)
	}

	return true, nil
}
